<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use App\Http\Controllers\ScoreRuleController;
use App\Models\BookHomeCollect;
use App\Models\HotSearch;
use App\Models\BookHomeOrder;
use App\Models\BookHomeOrderBook;
use App\Models\BookHomeOrderAddress;
use App\Models\BookHomePostageSet;
use App\Models\BookHomePostalRev;
use App\Models\BookHomePurchase;
use App\Models\BookHomePurchaseSet;
use App\Models\BookHomeSchoolbag;
use App\Models\Shop;
use App\Models\ShopBook;
use App\Models\ShopBookType;
use App\Models\UserAddress;
use App\Models\UserLibraryInfo;
use App\Validate\NewBookValidate;
use Exception;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

/**
 * 新书采购清单(书店书籍)
 * Class NewBookRecom
 * @package app\port\controller
 */
class NewBookRecomController extends CommonController
{
    private $model = null;
    private $validate = null;

    public function __construct()
    {
        parent::__construct();
        $this->model = new ShopBook();
        $this->validate = new NewBookValidate();
    }

    /**
     * 书店筛选列表
     */
    public function shopFiltrateList()
    {
        $shopModel = new Shop();
        $res = $shopModel->wechatShopFiltrateList();
        if (empty($res)) {
            return $this->returnApi(203, '暂无数据');
        }
        return $this->returnApi(200, '获取成功', true, $res);
    }

    /**
     * 新书类型筛选列表
     * @param shop_id int 书店id    0 为全部
     */
    public function bookTypeFiltrateList()
    {
        $shop_id = $this->request->input('shop_id', '');
        // if(empty($shop_id)){
        //     return $this->returnApi(201, '参数错误');
        // }

        $data =  Cache::get($shop_id . 'bookTypeFiltrateList');
        if (!empty($data)) {
            return $this->returnApi(200, '获取成功', true, $data);
        }

        $shopBookTypeModel = new ShopBookType();
        $res = $shopBookTypeModel->bookTypeFiltrateList($shop_id);
        if ($res) {
            foreach ($res as $key => $val) {
                $is_exists = $this->model->where('type_id', $val['id'])->where('is_plane', 1)->value('id');
                if (empty($is_exists)) {
                    unset($res[$key]); //不存在不显示
                } else {
                    if (empty($shop_id)) {
                        $res[$key]['type_name'] = $val['type_name'] . ' (' . $val['shop_name'] . ')'; //解决同一个类型，多家书店同时存在的情况
                    } else {
                        $res[$key]['type_name'] = $val['type_name'];
                    }
                }
            }
            //判断是否存在其他
            $is_exists = $this->model->whereRaw('type_id = 0 or type_id is null')->where('is_plane', 1)
                ->where(function ($query) use ($shop_id) {
                    if ($shop_id) {
                        $query->where('shop_id', $shop_id);
                    }
                })->value('id');

            $res = array_values($res); //正常排序
            if ($is_exists) $res[] = ['shop_name' => '', 'id' => 0, 'type_name' => '其他']; //如果存在无分类的数据才有其他

            Cache::put($shop_id . 'bookTypeFiltrateList', $res, 180);

            return $this->returnApi(200, '获取成功', true, $res);
        }
        // $res = [['shop_name' => '', 'id' => 0, 'name' => '其他']];//失败返回一个状态
        return $this->returnApi(200, '获取成功', true, $res);
        // return $this->returnApi( 203 , '暂无数据');
    }

    /**
     * 获取书籍列表
     * @param $book_id 书籍id
     */
    // public function getListById($book_id = [])
    // {
    //     $res = $this->select('id', 'book_name', 'author', 'author', 'pre_time', 'isbn', 'price', 'book_selector')
    //         ->whereIn('id', $book_id)
    //         ->get();
    //     return $res;
    // }

    /**
     * 新书列表
     * @param token ：用户 token  可选
     * @param shop_id  书店id   0、全部
     * @param keywords_type  检索条件   0、全部  1、书名  2、作者 3 isbn   默认 0
     * @param keywords  检索条件
     * @param book_selector  是否套书  0、全部 1 是  2 否   默认 0
     * @param is_recom  是否为推荐图书  0、全部 1 是 2 否   默认 0
     * @param type_id  类型id   0 为其他（type_id 为0的时候，书店id必须存在）  空为全部
     * @param page  页数，默认为1，
     * @param limit  条数，默认显示 10条
     */
    public function newBookList()
    {

        $shop_id = $this->request->input('shop_id', '');
        $keywords_type = $this->request->input('keywords_type', '');
        $keywords = $this->request->input('keywords', '');
        $book_selector = $this->request->input('book_selector', '2'); //只加载非套书
        $is_recom = $this->request->input('is_recom', '');
        $type_id = $this->request->input('type_id', '');
        $page = intval($this->request->input('page', 1)) ?: 1;
        $limit = intval($this->request->input('limit', 10)) ?: 10;
        $user_id = $this->request->user_info['id'];

        $keywords = addslashes($keywords);

        $not_allow_year = BookHomePurchaseSet::where('type', 11)->value('number');
        $res = $this->model->lists(
            ['n.id', 'type_id', 'n.book_name', 'n.author', 'n.press', 'n.pre_time',  'n.isbn', 'n.number', 'n.img', 'n.is_recom', 'n.create_time'],
            $shop_id,
            $keywords,
            $keywords_type,
            $type_id,
            $book_selector,
            $is_recom,
            1,
            null,
            $not_allow_year,
            null,
            $limit
        );

        if ($res['data']) {
            //添加检索热词
            if (!empty($keywords)) {
                $hotSearchModel = new HotSearch();
                $hotSearchModel->hotSearchAdd($keywords, 1);
            }
            foreach ($res['data'] as $key => $val) {
                //$res['data'][$key]['collect_num'] = BookCollectModel::where('book_id', $val['id'])->where('type' , 2)->count();
                //判断是否收藏
                if (!empty($user_id)) {
                    $isSchoolbag = BookHomeSchoolbag::isSchoolbag($val['id'], $user_id, 1);
                    $res['data'][$key]['is_schoolbag'] = empty($isSchoolbag) ? false : true; //是否加入书袋

                    $isCollect = BookHomeCollect::isCollect($val['id'], $user_id, 1);
                    $res['data'][$key]['is_collect'] = empty($isCollect) ? false : true; //是否收藏
                } else {
                    $res['data'][$key]['is_collect'] = false; //是否收藏
                    $res['data'][$key]['is_schoolbag'] = false; //是否加入书袋
                }
            }

            $res = $this->disPageData($res);
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 新书详情
     * @param book_id 书籍id
     * @param token ：用户 token  可选
     */
    public function newBookDetail()
    {
        // 自动验证
        if (!$this->validate->scene('new_book_detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $user_id = $this->request->user_info['id'];

        $data = $this->model->detail($this->request->book_id);
        if (empty($data)) {
            return $this->returnApi(203, '暂无数据');
        }

        $data = $data->toArray();

        //判断是否收藏 和 是否加入购物车
        if (!empty($user_id)) {
            $isCollect = BookHomeCollect::isCollect($this->request->book_id, $user_id, 1);
            $data['is_collect'] = empty($isCollect) ? false : true; //是否收藏
            $isSchoolbag = BookHomeSchoolbag::isSchoolbag($this->request->book_id, $user_id);
            $data['is_schoolbag'] = empty($isSchoolbag) ? false : true; //是否加入书袋
            //书袋书籍数量
            $data['schoolbag_number'] = BookHomeSchoolbag::where('user_id', $user_id)
                ->where('type', 1)
                ->count();
        } else {
            $data['is_collect'] = false; //未收藏
            $data['is_schoolbag'] = false; //未加入书袋
            $data['schoolbag_number'] = 0; //书袋数量
        }
        $data['intros'] = strip_tags($data['intro']);
        //获取同类书籍
        $data['other_data'] = $this->model->getLikeBook($data['id'], $data['shop_id'], $data['type_id']);

        //判断是否加入书袋
        if (!empty($data['other_data'])) {
            if (!empty($user_id)) {
                $isSchoolbag = BookHomeSchoolbag::isSchoolbag($data['other_data']['id'], $user_id, 1);
                $data['other_data']['is_schoolbag'] = empty($isSchoolbag) ? false : true; //是否加入书袋
                $isCollect = BookHomeCollect::isCollect($this->request->book_id, $user_id, 1);
                $data['is_collect'] = empty($isCollect) ? false : true; //是否收藏
            } else {
                $data['other_data']['is_schoolbag'] = false; //是否加入书袋
                $data['other_data']['is_collect'] = false; //是否收藏
            }

            $data['other_data'] = $data['other_data']->toArray();
            $data['other_data'] = $this->disDataSameLevel($data['other_data'], 'get_shop_name', ['shop_name' => 'shop_name']);
            $data['other_data'] = $this->disDataSameLevel($data['other_data'], 'get_type_name', ['type_name' => 'type_name']);
        }

        //获取新书封面
        if ($data['access_number'] <= 5 && ($data['img'] == 'default/default_new_book.png' || $data['img'] == '/default/default_new_book.png' || empty($data['img']))) {
            $controllerObj = new Controller();
            $img = $controllerObj->getImgByIsbn($data['isbn']);
            $change_img['access_number'] = $data['access_number'] + 1;
            if ($img) {
                $change_img['img'] = $img;
                $data['img'] = $img; //立即返回图片
            }
            $this->model->where('id', $this->request->book_id)->update($change_img);
        }

        return $this->returnApi(200, '获取成功', true, $data);
    }

    /**
     * 我的新书收藏列表
     * @param token ：用户 token
     * @param page  页数，默认为1，
     * @param limit  条数，默认显示 10条
     */
    public function myNewBookCollectList()
    {
        $user_id = $this->request->user_info['id'];
        $page = intval($this->request->input('page', 1)) ?: 1;
        $limit = intval($this->request->input('limit', 10)) ?: 10;

        $res = BookHomeCollect::select('id', 'book_id', 'create_time')
            ->with(['newBookCollect' => function ($query) {
                $query->select(['id', 'book_name', 'author', 'press', 'pre_time', 'isbn', 'price', 'img', 'intro', 'shop_id']);
            }])
            ->whereHas('newBookCollect', function ($query) {
                $query->where('is_del', 1);
            })
            ->where('user_id', $user_id)
            ->where('type', 1)
            ->orderByDesc('id')
            ->paginate($limit)
            ->toArray();

        foreach ($res['data'] as &$val) {
            $val['book_name'] = $val['new_book_collect']['book_name'];
            $val['author'] = $val['new_book_collect']['author'];
            $val['press'] = $val['new_book_collect']['press'];
            $val['pre_time'] = $val['new_book_collect']['pre_time'];
            $val['isbn'] = $val['new_book_collect']['isbn'];
            $val['price'] = $val['new_book_collect']['price'];
            $val['img'] = $val['new_book_collect']['img'];
            $val['intro'] = $val['new_book_collect']['intro'];
            $val['shop_name'] = Shop::where('id', $val['new_book_collect']['shop_id'])->value('name');

            unset($val['id']);
            unset($val['new_book_collect']);
        }

        if (!empty($res['data'])) {
            $res = $this->disPageData($res);
            return $this->returnApi(200, '获取成功', true, $res['data']);
        }
        return $this->returnApi(203, '获取失败');
    }

    /**
     * 新书加入书袋与移出书袋
     * @param  token ：用户 token
     * @param  $book_id 书籍id
     */
    public function newBookSchoolbag()
    {
        // 自动验证
        if (!$this->validate->scene('new_book_schoolbag')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $user_id = $this->request->user_info['id'];

        $book_id = $this->request->book_id;
        $res = BookHomeSchoolbag::isSchoolbag($book_id, $user_id, 1);
        if (empty($res)) {
            $isbn = $this->model->where('id', $book_id)->value('isbn');
            $result = BookHomePurchase::where('isbn', $isbn)->where('user_id', $user_id)->first();

            if ($result) {
                return $this->returnApi(202, '此书籍已采购，不允许加入书袋');
            }
            //判断此书是否已购买或已采购
            $bookHomeOrderModel = new BookHomeOrder();
            $state = $bookHomeOrderModel->from($bookHomeOrderModel->getTable() . ' as n')
                ->join('book_home_order_book as b', 'b.order_id', '=', 'n.id')
                ->where('b.book_id', $book_id)
                ->where('n.user_id', $user_id)
                ->where('b.type', 1)
                ->where(function ($query) {
                    $query->where('n.is_pay', 1)
                        ->Orwhere('n.is_pay', 2)
                        ->Orwhere('n.is_pay', 6)
                        ->Orwhere('n.is_pay', 8);
                })->first();

            if (!empty($state)) {
                return $this->returnApi(202, '此书已在采购流程中，不允许加入书袋');
            }

            //加入书袋，书袋数量不能超过 100 个
            $count = BookHomeSchoolbag::where('user_id', $user_id)->where('type', 1)->count();
            if ($count > 100) {
                return $this->returnApi(202, '加入失败，书袋书籍不能超过100本');
            }
            $newSchoolbagModel = new BookHomeSchoolbag();
            $result = $newSchoolbagModel->add([
                'user_id' => $user_id,
                'book_id' => $book_id,
                'type' => 1,
            ]);
            $msg = '加入书袋';
        } else {
            $result = $res->delete();
            $msg = '移出书袋';
        }
        if ($result) {
            return $this->returnApi(200, $msg . '成功', true);
        }
        return $this->returnApi(202, $msg . '失败');
    }

    /**
     * 我的新书书袋列表
     * @param  token ：用户 token
     * //* @param page  页数，默认为1，
     * //* @param limit  条数，默认显示 10条
     */
    public function myNewBookSchoolbagList()
    {
        $user_id = $this->request->user_info['id'];
        $newSchoolbagModel = new BookHomeSchoolbag();

        $res = $newSchoolbagModel->myNewBookSchoolbagList($user_id);

        $data = [];
        foreach ($res as &$val) {
            unset($val['id']);
            unset($val['new_book_schoolbag']);
            if (!isset($data[$val['shop_id']]['shop_name'])) {
                $data[$val['shop_id']]['shop_id'] = $val['shop_id'];
                $data[$val['shop_id']]['shop_name'] = Shop::where('id', $val['shop_id'])->value('name');
            }

            $val['number'] = ShopBook::where('id', $val['book_id'])->value('number'); //库存数量

            $data[$val['shop_id']]['data'][] = $val;
        }
        if (!empty($data)) {
            sort($data);

            return $this->returnApi(200, '获取成功', true, $data);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 获取订单预估金额
     * @param  token ：用户 token
     * @param  $book_ids  书籍id 多本书用 ， 逗号 拼接
     */
    public function getOrderForecastPrice()
    {
        // 自动验证
        if (!$this->validate->scene('get_order_forecast_price')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $user_id = $this->request->user_info['id'];
        $account_id = $this->request->user_info['account_id'];
        $book_ids = $this->request->book_ids;
        $book_ids = explode(',', $book_ids);

        //验证密码是否正确
        $userLibraryInfoModel = new UserLibraryInfo();
        $account_info = $userLibraryInfoModel->checkAccountPwdIsNormal($user_id);
        if (is_string($account_info)) {
            return $this->returnApi(204, $account_info);
        }

        DB::beginTransaction();
        try {
            $bookHomeOrderModel = new BookHomeOrder();
            //获取邮费价格
            $postage_price = BookHomePostageSet::where('type', 1)
                ->where('number', count($book_ids))
                ->value('price');
            if (empty($postage_price)) {
                throw new \Exception('后台邮费设置不正确，请联系管理员处理');
            }

            $postageBudget = $bookHomeOrderModel->getPostageBudget($postage_price, $account_id);  //需要自己支付邮费

            $dis_price = $postageBudget ? 0 : $postage_price; //0 表示不支付 //图书馆支付邮费

            DB::commit();
            return $this->returnApi(200, '获取成功', true, [
                'dis_price' => $dis_price, //预估金额
                'price' => $postage_price, //实际金额
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }


    /**
     * 获取预支付订单信息
     * @param  token ：用户 token
     * @param  $book_ids  书籍id 多本书用 ， 逗号 拼接
     * @param  $address_id 收货地址id
     */
    public function getOrderInfo()
    {
        // 自动验证
        if (!$this->validate->scene('get_order_info')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $user_id = $this->request->user_info['id'];
        $account_id = $this->request->user_info['account_id'];


        //验证密码是否正确
        $userLibraryInfoModel = new UserLibraryInfo();
        $account_info = $userLibraryInfoModel->checkAccountPwdIsNormal($user_id);
        if (is_string($account_info)) {
            return $this->returnApi(204, $account_info);
        }

        DB::beginTransaction();
        try {
            $bookHomeOrderModel = new BookHomeOrder();
            $bookHomeOrderBookModel = new BookHomeOrderBook();
            //判断用户借阅权限
            $book_ids_array = $this->model->checkNewBookBorrowAuth($account_id, $this->request->book_ids, false);

            //判断用户积分是否满足要求
            $scoreRuleObj = new ScoreRuleController();
            $score_status = $scoreRuleObj->checkScoreStatus(8, $user_id, $account_id);
            if ($score_status['code'] == 202 || $score_status['code'] == 203) {
                throw new Exception($score_status['msg']);
            }

            $order_number = get_order_id();
            //获取邮费价格
            $postage_price = BookHomePostageSet::where('type', 1)
                ->where('number', count($book_ids_array['book_id']))
                ->value('price');
            if (empty($postage_price)) {
                throw new \Exception('后台邮费设置不正确，请联系管理员处理');
            }

            $postageBudget = $bookHomeOrderModel->getPostageBudget($postage_price, $account_id);

            if ($postageBudget) {
                //图书馆支付邮费
                $dis_price = 0;
                $discount = 0; //表示不支付
                $is_pay = 2; //直接支付成功
                $payment = 2; //图书馆邮费支付
                $change_time = date('Y-m-d H:i:s'); //支付时间
                $msg = '申请提交成功,等待后台管理员审核，本单邮费由图书馆统一支付！';
            } else {
                //需要自己支付邮费
                $dis_price = $postage_price;
                $discount = 100; //表示全额支付
                $is_pay = 1; //表示全额支付
                $payment = 1; //微信支付
                $change_time = null; //支付时间
                $msg = '下订单成功';
            }


            //添加新书订单表
            $create_time = date('Y-m-d H:i:s');
            $bookHomeOrderModel->add([
                'order_number' => $order_number,
                'user_id' => $user_id,
                'account_id' => $account_id,
                'shop_id' => $book_ids_array['shop_id'],
                'price' => $postage_price,
                'dis_price' => $dis_price,
                'discount' => $discount,
                'is_pay' => $is_pay,
                'create_time' => $create_time,
                'expire_time' => date('Y-m-d H:i:s', strtotime("+30 minute", strtotime($create_time))), //订单过期时间，默认30分钟
                'change_time' => $change_time,
                'payment' => $payment,
                'type' => 1,
            ]);

            //添加订单地址
            $address_info = UserAddress::find($this->request->address_id);
            $orderAddressModel = new BookHomeOrderAddress();
            $orderAddressModel->add([
                'order_id' => $bookHomeOrderModel->id,
                'username' => $address_info['username'],
                'tel' => $address_info['tel'],
                'province' => $address_info['province'],
                'city' => $address_info['city'],
                'district' => $address_info['district'],
                'street' => $address_info['street'],
                'address' => $address_info['address']
            ]);

            //添加新书订单书籍表
            $order_book = [];
            foreach ($book_ids_array['book_id'] as $v) {
                $order_book[] = [
                    'order_id' => $bookHomeOrderModel->id,
                    'book_id' => $v,
                    'type' => 1,
                    'create_time' => date('Y-m-d H:i:s'),
                ];

                //较少库存
                $res = ShopBook::modifyRepertoryNumber($v, 2);
                if ($res !== true) {
                    throw new \Exception($res);
                }
            }
            $bookHomeOrderBookModel->insert($order_book);

            if ($postageBudget) {
                //添加推送模板消息
                // $tempInfo = new \app\common\controller\TempInfo();
                // $data['openid'] = \app\common\controller\Common::getOpenIdByUserId(self::$param['user_id']);
                // $data['username'] = UserLibraryInfoModel::where('id', $account_id)->value('username');
                // $data['msg'] = '在线借阅';
                // $data['msg1'] = '新书';
                // $data['msg2'] = '请随时关注审核进度！';
                // $data['create_time'] = $change_time;
                // $data['link'] = '?booktype=1&id=' . $bookHomeOrderModel->id;
                // $tempInfo->sendTempInfoApplySuccess($data);

                $this->systemAdd('书籍采购提交成功', $user_id, $account_id, 36, $bookHomeOrderModel->id, '书籍采购提交成功，等待后台管理员审核，请随时关注审核进度！');
            }

            DB::commit();
            return $this->returnApi(200, $msg, true, [
                'order_id' => $bookHomeOrderModel->id,
                'order_number' => $order_number,
                'create_time' => $create_time,
                'price' => $postage_price,
                'postage_budget' => $postageBudget,
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 我的 新书 订单列表
     * @param token ：用户 token
     * @param $page  页数，默认为1，
     * @param $limit  条数，默认显示 10条
     */
    public function myOrderList()
    {
        //处理已失效的订单
        BookHomeOrder::checkNoPayOrder();

        $user_id = $this->request->user_info['id'];
        $page = intval($this->request->input('page', 1)) ?: 1;
        $limit = intval($this->request->input('limit', 10)) ?: 10;

        //判断读者证号密码是否正确
        // $account_id = '';
        //  if (config('other.is_validate_lib_api')) {
        $userLibraryInfoModel = new UserLibraryInfo();
        $account_lib_info = $userLibraryInfoModel->checkAccountPwdIsNormal($user_id);
        if (is_string($account_lib_info)) {
            return $this->returnApi(204, $account_lib_info);
        }
        $account_id =  $account_lib_info['id'];
        //  }

        $bookHomeOrderModel = new BookHomeOrder();
        $res = $bookHomeOrderModel->select('id', 'order_number', 'price', 'is_pay', 'create_time', 'change_time', 'refund_time', 'agree_time', 'deliver_time')
            ->with(['getOrderBookInfo' => function ($query) {
                $query->select('book_id', 'order_id', 'book_name', 'author', 'press', 'isbn', 'price', 'img');
            }])
            ->where(function ($query) use ($user_id, $account_id) {
                if ($account_id) {
                    $query->where('account_id', $account_id);
                } else {
                    $query->where('user_id', $user_id);
                }
            })
            //->order('is_pay' , 'asc')
            ->where('type', 1)
            ->orderByDesc('id')
            ->paginate($limit)
            ->toArray();

        if ($res['data']) {
            $res = $this->disPageData($res);
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 我的新书订单详情
     * @param token ：用户 token
     * @param $order_id ：订单id
     */
    public function myOrderDetail()
    {
        if (!$this->validate->scene('my_order_detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $user_id = $this->request->user_info['id'];
        $order_id = $this->request->order_id;

        //判断读者证号密码是否正确
        $userLibraryInfoModel = new UserLibraryInfo();
        $account_lib_info = $userLibraryInfoModel->checkAccountPwdIsNormal($user_id);
        if (is_string($account_lib_info)) {
            return $this->returnApi(204, $account_lib_info);
        }
        $account_id =  $account_lib_info['id'];

        $bookHomeOrderModel = new BookHomeOrder();
        //查看当前订单是否失效
        BookHomeOrder::checkNoPayOrder($order_id);

        $res = $bookHomeOrderModel->select('id', 'shop_id', 'order_number', 'tracking_number', 'price', 'dis_price', 'is_pay', 'payment', 'create_time', 'expire_time', 'change_time', 'refund_time', 'agree_time', 'deliver_time', 'cancel_time', 'cancel_remark', 'refund_remark')
            ->with(['getOrderAddress' => function ($query) {
                $query->select('id', 'order_id', 'username', 'tel', 'province', 'city', 'district', 'street', 'address');
            }, 'getOrderBookInfo' => function ($query) {
                $query->select('book_name', 'author', 'press', 'pre_time', 'img', 'isbn', 'price');
            }])
            ->where(function ($query) use ($user_id, $account_id) {
                if ($account_id) {
                    $query->where('account_id', $account_id);
                } else {
                    $query->where('user_id', $user_id);
                }
            })
            ->where('id', $order_id)
            ->first();
        if ($res) {
            $res = $res->toArray();
            // $res['create_time'] = date('Y/m/d H:i:s', strtotime($res['create_time']));
            // $res['expire_time'] = $res['expire_time'] ? date('Y/m/d H:i:s', strtotime($res['expire_time'])) : null;
            // $res['change_time'] = $res['change_time'] ? date('Y/m/d H:i:s', strtotime($res['change_time'])) : null;
            // $res['agree_time'] = $res['agree_time'] ? date('Y/m/d H:i:s', strtotime($res['agree_time'])) : null;
            // $res['refund_time'] = $res['refund_time'] ? date('Y/m/d H:i:s', strtotime($res['refund_time'])) : null;
            // $res['deliver_time'] = $res['deliver_time'] ? date('Y/m/d H:i:s', strtotime($res['deliver_time'])) : null;
            // $res['cancel_time'] = $res['cancel_time'] ? date('Y/m/d H:i:s', strtotime($res['cancel_time'])) : null;

            //获取运单轨迹
            if (!empty($res['tracking_number'])) {
                $postalRevModel = new BookHomePostalRev();
                $res['track'] = $postalRevModel->getTrack($res['tracking_number']);
            } else {
                $res['track'] = null;
            }
            $res['shop_name'] = Shop::where('id', $res['shop_id'])->value('name');

            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }
}
